﻿using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

namespace CloudShot.Core.Utils
{
  public static class Base64Utils
  {
    public static string SerializeToBase64<T>(T value)
    {
      if (Equals(value, default(T)))
        return null;

      // Serialize to a base 64 string
      using (var memoryStream = new MemoryStream())
      {
        var binaryFormatter = new BinaryFormatter();
        binaryFormatter.Serialize(memoryStream, value);
        
        byte[] bytes = memoryStream.GetBuffer();
        
        return Convert.ToBase64String(bytes, 0, bytes.Length, Base64FormattingOptions.None);
      }
    }

    public static T DeserializeFromBase64<T>(string value)
    {
      if (string.IsNullOrEmpty(value))
        return default(T);

      // Extract data from the base 64 string!
      byte[] memorydata = Convert.FromBase64String(value);
      using (var memoryStream = new MemoryStream(memorydata))
      {
        var binaryFormatter = new BinaryFormatter();
        return (T)binaryFormatter.Deserialize(memoryStream);
      }
    }
  }
}